#include "buffer.h"
#include <cstring>

// 构造函数初始化 err
Buffer::Buffer() : buf(nullptr), length(0), capacity(0), readIndex(0), err(Err_t::NO_ERROR) {}
// 析构函数
Buffer::~Buffer()
{
    delete[] buf;
}


// 设置错误状态的私有方法
void Buffer::setError(Err_t error)
{
    err = error;
}

// 获取错误状态的接口
Buffer::Err_t Buffer::getError() const
{
    return err;
}

// 自动管理 index 顺序的读取方法实现
uint32_t Buffer::read_u32(DataTyep_t type)
{
    if (readIndex + 4 > length)
    {
        setError(Err_t::INDEX_OUT_OF_RANGE);
        return 0;
    }
    uint32_t result = to_u32(readIndex, type);
    readIndex += 4;
    return result;
}

uint16_t Buffer::read_u16(DataTyep_t type)
{
    if (readIndex + 2 > length)
    {
        setError(Err_t::INDEX_OUT_OF_RANGE);
        return 0;
    }
    uint16_t result = to_u16(readIndex, type);
    readIndex += 2;
    return result;
}
uint8_t Buffer::read_u8()
{
    if (readIndex + 1 > length)
    {
        setError(Err_t::INDEX_OUT_OF_RANGE);
        return 0;
    }
    uint8_t result = buf[readIndex];
    readIndex += 1;
    return result;
}

int32_t Buffer::read_i32(DataTyep_t type)
{
    if (readIndex + 4 > length)
    {
        setError(Err_t::INDEX_OUT_OF_RANGE);
        return 0;
    }
    int32_t result = to_i32(readIndex, type);
    readIndex += 4;
    return result;
}

int16_t Buffer::read_i16(DataTyep_t type)
{
    if (readIndex + 2 > length)
    {
        setError(Err_t::INDEX_OUT_OF_RANGE);
        return 0;
    }
    int16_t result = to_i16(readIndex, type);
    readIndex += 2;
    return result;
}

int8_t Buffer::read_i8()
{
    if (readIndex + 1 > length)
    {
        setError(Err_t::INDEX_OUT_OF_RANGE);
        return 0;
    }
    int8_t result = static_cast<int8_t>(buf[readIndex]);
    readIndex += 1;
    return result;
}
float Buffer::read_float(DataTyep_t type)
{
    if (readIndex + 4 > length)
    {
        setError(Err_t::INDEX_OUT_OF_RANGE);
        return 0.0f;
    }
    float result = to_float(readIndex, type);
    readIndex += 4;
    return result;
}

Buffer Buffer::read_buf(uint16_t size) {
    Buffer result;
    if (readIndex + size > length) {
        setError(Err_t::INDEX_OUT_OF_RANGE);
        return result;
    }

    result.append(buf + readIndex, size);
    readIndex += size;
    return result;
}

String Buffer::read_String() {
    String result;
    // 查找空字符的位置
    uint16_t endIndex = readIndex;
    while (endIndex < length && buf[endIndex] != '\0') {
        endIndex++;
    }

    if (endIndex == length) {
        // 没有找到空字符，设置错误
        setError(Err_t::INDEX_OUT_OF_RANGE);
        return result;
    }

    // 计算字符串长度
    uint16_t strLength = endIndex - readIndex;
    // 读取字符串
    for (uint16_t i = 0; i < strLength; i++) {
        result += static_cast<char>(buf[readIndex + i]);
    }
    // 移动 readIndex 到空字符之后
    readIndex = endIndex + 1;

    return result;
}

// 实现设置 readIndex 的接口
void Buffer::setReadIndex(uint16_t newIndex)
{
    if (newIndex > length)
    {
        setError(Err_t::INDEX_OUT_OF_RANGE);
        return;
    }
    readIndex = newIndex;
    setError(Err_t::NO_ERROR); // 操作成功，清除错误状态
}
uint16_t Buffer::getReadIndex() const
{
    return readIndex;
}

// 清空缓冲区时重置 err
void Buffer::clear()
{
    delete[] buf;
    buf = nullptr;
    length = 0;
    capacity = 0;
    readIndex = 0;
    err = Err_t::NO_ERROR;
}



// 扩容函数
void Buffer::expandCapacity(uint16_t minRequired)
{
    uint16_t newCapacity = capacity == 0 ? 4 : capacity * 2;
    while (newCapacity < minRequired)
    {
        newCapacity *= 2;
    }

    uint8_t *newBuf = new uint8_t[newCapacity];
    if (buf)
    {
        std::memcpy(newBuf, buf, length);
        delete[] buf;
    }
    buf = newBuf;
    capacity = newCapacity;
}

// 追加 uint32_t 类型数据
void Buffer::append_u32(uint32_t value, DataTyep_t type)
{
    uint16_t newLength = length + 4;
    if (newLength > capacity)
    {
        expandCapacity(newLength);
    }

    if (type == LittleEnd)
    {
        for (int i = 0; i < 4; ++i)
        {
            buf[length + i] = static_cast<uint8_t>(value >> (i * 8));
        }
    }
    else
    {
        for (int i = 0; i < 4; ++i)
        {
            buf[length + i] = static_cast<uint8_t>(value >> ((3 - i) * 8));
        }
    }
    length = newLength;
}

// 追加 uint16_t 类型数据
void Buffer::append_u16(uint16_t value, DataTyep_t type)
{
    uint16_t newLength = length + 2;
    if (newLength > capacity)
    {
        expandCapacity(newLength);
    }

    if (type == LittleEnd)
    {
        buf[length] = static_cast<uint8_t>(value & 0xFF);
        buf[length + 1] = static_cast<uint8_t>(value >> 8);
    }
    else
    {
        buf[length] = static_cast<uint8_t>(value >> 8);
        buf[length + 1] = static_cast<uint8_t>(value & 0xFF);
    }
    length = newLength;
}

// 追加 uint8_t 类型数据
void Buffer::append_u8(uint8_t value)
{
    uint16_t newLength = length + 1;
    if (newLength > capacity)
    {
        expandCapacity(newLength);
    }

    buf[length] = value;
    length = newLength;
}

// 从指定索引获取 uint32_t 类型数据
uint32_t Buffer::to_u32(uint16_t index, DataTyep_t type)
{
    if (index + 4 > length)
    {
        return 0;
    }
    uint32_t result = 0;
    if (type == LittleEnd)
    {
        for (int i = 0; i < 4; ++i)
        {
            result |= static_cast<uint32_t>(buf[index + i]) << (i * 8);
        }
    }
    else
    {
        for (int i = 0; i < 4; ++i)
        {
            result |= static_cast<uint32_t>(buf[index + i]) << ((3 - i) * 8);
        }
    }
    return result;
}

// 从指定索引获取 uint16_t 类型数据
uint16_t Buffer::to_u16(uint16_t index, DataTyep_t type)
{
    if (index + 2 > length)
    {
        return 0;
    }
    uint16_t result = 0;
    if (type == LittleEnd)
    {
        result = static_cast<uint16_t>(buf[index]) | (static_cast<uint16_t>(buf[index + 1]) << 8);
    }
    else
    {
        result = static_cast<uint16_t>(buf[index + 1]) | (static_cast<uint16_t>(buf[index]) << 8);
    }
    return result;
}

// 从指定索引获取 int32_t 类型数据
int32_t Buffer::to_i32(uint16_t index, DataTyep_t type)
{
    return static_cast<int32_t>(to_u32(index, type));
}

// 从指定索引获取 int16_t 类型数据
int16_t Buffer::to_i16(uint16_t index, DataTyep_t type)
{
    return static_cast<int16_t>(to_u16(index, type));
}

// 从指定索引获取 float 类型数据
float Buffer::to_float(uint16_t index, DataTyep_t type)
{
    if (index + 4 > length)
    {
        return 0.0f;
    }
    uint32_t intValue = to_u32(index, type);
    float result;
    std::memcpy(&result, &intValue, sizeof(float));
    return result;
}

void Buffer::append(const uint8_t *data, uint16_t size)
{
    uint16_t newLength = length + size;
    if (newLength > capacity)
    {
        expandCapacity(newLength);
    }
    std::memcpy(buf + length, data, size);
    length = newLength;
}
void Buffer::append(const char *str)
{
    if (str == nullptr)
    {
        return;
    }
    uint16_t strLength = static_cast<uint16_t>(strlen(str));
    uint16_t newLength = length + strLength;
    if (newLength > capacity)
    {
        expandCapacity(newLength);
    }
    memcpy(buf + length, str, strLength);
    length = newLength;
}

void Buffer::append(const Buffer &other)
{
    uint16_t newLength = length + other.length;
    if (newLength > capacity)
    {
        expandCapacity(newLength);
    }
    memcpy(buf + length, other.buf, other.length);
    length = newLength;
}
const uint8_t *Buffer::data() const
{
    return buf;
}

uint16_t Buffer::size() const
{
    return length;
}


// 移动赋值运算符
Buffer &Buffer::operator=(Buffer &&other) noexcept
{
    if (this != &other)
    {
        delete[] buf;
        buf = other.buf;
        length = other.length;
        capacity = other.capacity;
        other.buf = nullptr;
        other.length = 0;
        other.capacity = 0;
    }
    return *this;
}

// 重载 + 运算符，合并两个 Buffer 对象
Buffer Buffer::operator+(const Buffer &other) const
{
    Buffer result(*this);
    result.append(other.buf, other.length);
    return result;
}


// 复制构造函数
Buffer::Buffer(const Buffer &other) : length(other.length), capacity(other.capacity)
{
    buf = new uint8_t[capacity];
    std::memcpy(buf, other.buf, length);
}

// 复制赋值运算符实现
Buffer& Buffer::operator=(const Buffer &other) {
    if (this != &other) {
        // 释放当前对象的资源
        delete[] buf;
        
        // 复制其他对象的属性
        length = other.length;
        capacity = other.capacity;
        readIndex = other.readIndex;
        err = other.err;
        
        // 复制数据
        buf = new uint8_t[capacity];
        for (uint16_t i = 0; i < length; ++i) {
            buf[i] = other.buf[i];
        }
    }
    return *this;
}

// 移动构造函数
Buffer::Buffer(Buffer &&other) noexcept : buf(other.buf), length(other.length), capacity(other.capacity)
{
    other.buf = nullptr;
    other.length = 0;
    other.capacity = 0;
}